import request from '@/utils/request'

export default {
  namespaced: true,
  state () {
    return {
      cartList: []
    }
  },
  mutations: {
    setCartList (state, newList) {
      state.cartList = newList
    },
    toggleCheck (state, goodsId) {
      const goods = state.cartList.find(item => item.item.id === goodsId)
      goods.isChecked = !goods.isChecked
    },
    toggleAllCheck (state, flag) {
      state.cartList.forEach(item => {
        item.isChecked = flag
      })
    },
    changeCount (state, { id, value }) {
      const obj = state.cartList.find(item => item.item.id === id)
      obj.num = value
    }
  },
  actions: {
    async getCartAction (context) {
      const res = await request({
        url: '/shopping-cart/cart-list',
        method: 'get'
      })
      let cartList = res.data.data
      const carts = []
      cartList.forEach(item => {
        const cart = {
          item: {},
          isChecked: true
        }
        cart.item = item
        if (cart.item.flavorString !== '') {
          cart.item.flavorString = JSON.parse(cart.item.flavorString)
          let flavorList = ''
          cart.item.flavorString.forEach(flavor => {
            flavorList += (flavor + '+')
          })
          flavorList = flavorList.slice(0, -1)
          cart.item.flavorString = flavorList
        }
        carts.push(cart)
      })
      cartList = carts
      context.commit('setCartList', cartList)
    },
    async changeCountAction (context, obj) {
      const { id, num } = obj
      context.commit('changeCount', {
        id,
        num
      })
      await request({
        url: '/shopping-cart/shopping-cart',
        method: 'put',
        data: { id, num }
      })
      context.dispatch('getCartAction')
    },
    // 删除购物车数据
    async delSelect (context) {
      const selCartList = context.getters.selCartList
      const cartIds = selCartList.map(item => item.item.id)
      await request({
        url: '/shopping-cart/cart-list',
        method: 'delete',
        data: cartIds
      })

      // 重新拉取最新的购物车数据 (重新渲染)
      context.dispatch('getCartAction')
    }
  },
  getters: {
    cartTotal (state) {
      return state.cartList.reduce((sum, item, index) => sum + item.item.num, 0)
    },
    selCartList (state) {
      return state.cartList.filter(item => item.isChecked)
    },
    selCount (state, getters) {
      return getters.selCartList.reduce((sum, item, index) => sum + item.item.num, 0)
    },
    selPrice (state, getters) {
      return getters.selCartList.reduce((sum, item, index) => {
        return sum + item.item.num * item.item.totalMoney
      }, 0).toFixed(2)
    },
    isAllChecked (state) {
      return state.cartList.every(item => item.isChecked)
    }
  }
}
